package com.example.project10;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

public class SplashActivity extends AppCompatActivity {
    private static final int SPLASH_DURATION = 2000; // 2秒
    private LoginViewModel loginViewModel;
    private Handler handler;
    private Runnable redirectRunnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        // 初始化ViewModel
        loginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        
        // 观察自动登录结果
        observeAutoLoginResult();
        
        // 检查是否应该自动登录
        if (shouldAutoLogin()) {
            // 显示自动登录提示
            Toast.makeText(this, "自动登录中...", Toast.LENGTH_SHORT).show();
            // 执行自动登录
            loginViewModel.autoLogin();
        } else {
            // 延迟跳转到登录页面
            handler = new Handler();
            redirectRunnable = () -> redirectToLogin();
            handler.postDelayed(redirectRunnable, SPLASH_DURATION);
        }
    }

    private void observeAutoLoginResult() {
        loginViewModel.autoLoginResult.observe(this, result -> {
            if (result != null) {
                if (result.equals("SUCCESS")) {
                    Toast.makeText(SplashActivity.this, "自动登录成功", Toast.LENGTH_SHORT).show();
                    redirectToMain();
                } else {
                    // 自动登录失败，跳转到登录页面
                    String errorMessage = result.startsWith("ERROR: ") ? result.substring(7) : "自动登录失败";
                    Toast.makeText(SplashActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                    redirectToLogin();
                }
            }
        });
    }

    private boolean shouldAutoLogin() {
        return SharedPreferencesUtil.isAutoLoginEnabled(this) && 
               SharedPreferencesUtil.getToken(this) != null;
    }

    private void redirectToMain() {
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        intent.putExtra("user_email", "auto_login_user@example.com");
        startActivity(intent);
        finish();
    }

    private void redirectToLogin() {
        Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清理Handler回调，避免内存泄漏
        if (handler != null && redirectRunnable != null) {
            handler.removeCallbacks(redirectRunnable);
        }
    }
}